package com.tbit.uqbike.webmanager.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
/**
 * @description:
 * @author: chen
 * @create: 2024-01-18 15:52
 **/
@Slf4j
public class MergeObjectsUtil {

    //合并两个对象的值
    public static <T> T mergeObjects(T sourceBean, T targetBean) {

        Class sourceBeanClass = sourceBean.getClass();
        Class targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = targetBeanClass.getDeclaredFields();
        for (int i = 0; i < sourceFields.length; i++) {
            Field sourceField = sourceFields[i];
            Field targetField = targetFields[i];
            sourceField.setAccessible(true);
            targetField.setAccessible(true);

            Class<?> type = sourceField.getType();

            try {
                if (!ObjectUtils.isEmpty(sourceField.get(sourceBean))) {
                    targetField.set(targetBean, sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
        }
        return targetBean;
    }
}